package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

import javax.naming.NamingException;
import org.eclipse.jdt.annotation.NonNull;

import tool.DatabaseConnection;

public class EntityDAOImpl implements EntityDAO {
    private Connection conn;
    private static final int TIMEOUT = 3;
    private static final String INSERT_STATEMENT = "INSERT INTO ENTITY(ENTITY_NAME) VALUES(?)";
    private static final String SELECT_STATEMENT = "SELECT ENTITY_ID FROM ENTITY WHERE ENTITY_NAME=?";

    public EntityDAOImpl(@NonNull Connection conn) {
        this.conn = conn;
    }

    @Override
    public int add(@NonNull String value) {
        int state = 0;
        PreparedStatement ps = null;
        try {
            if (!conn.isValid(TIMEOUT)) {
                conn = DatabaseConnection.getConnection();
            }
            if (query(value) == 1) {
                return 0;
            }
            ps = conn.prepareStatement(INSERT_STATEMENT);
            ps.setString(1, value);
            state = ps.executeUpdate();
        } catch (SQLException | NamingException e) {
            state = -1;
        } finally {
            try {
                if (Objects.nonNull(ps)) {
                    ps.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return state;
    }

    @Override
    public int query(@NonNull String value) throws SQLException, NamingException {
        if (!conn.isValid(TIMEOUT)) {
            conn = DatabaseConnection.getConnection();
        }
        PreparedStatement ps = conn.prepareStatement(SELECT_STATEMENT);
        ps.setString(1, value);
        ResultSet rs = ps.executeQuery();
        int state = rs.next() ? 1 : 0;
        rs.close();
        ps.close();
        return state;
    }
}
